import React, { Component } from 'react'
import {
    Card,
    Form,
    Input,
    Cascader,
    Button,
    message
} from 'antd'
import { ArrowLeftOutlined } from '@ant-design/icons'

import LinkButton from '../../../components/link-button'
import {reqCategorys, reqAddOrUpdateProduct} from '../../../api'
import PicturesWall from '../picturesWall/picturesWall'
import RichTextEditor from '../richTextEditor/richTextEditor'

const {Item} = Form
const { TextArea } = Input
// 添加和更新的子路由
export default class ProductAddUpdate extends Component {

    constructor (props) {
        super(props)
        // 创建保存ref标识的对象容器
        this.pw = React.createRef()
        this.rte = React.createRef()

        this.state = {
            options: [],
        }

    }

    // 点击提交事件
    submit = async (values) => {
        // 表单验证，通过了才发送请求
        // 收集所有数据，并封装product对象
        const {name, desc, price, categoryIds} = values
        let pCategoryId, categoryId
        if (categoryIds.length === 1){
            pCategoryId = '0'
            categoryId = categoryIds[0]
        } else {
            pCategoryId = categoryIds[0]
            categoryId = categoryIds[1]
        }

        // 获取图片名
        const img = this.pw.current.getImgs()
        // 获取富文本信息
        const detail = this.rte.current.getDetail()
        
        const product = {
            productName: name,
            desc,
            price,
            img,
            detail,
            pcategoryId: pCategoryId,
            categoryId
        }

        // 如果是更新额外增加一个id
        if (this.isUpdate) {
            product.id = this.product.id
        }
        console.log("product", product)
        const reponse = await reqAddOrUpdateProduct(product)
        const result = reponse.data
        if (result.status === 0) {
            message.success((this.isUpdate ? '修改' : '添加') + '商品成功')
            this.props.history.goBack()
        } else {
            message.error((this.isUpdate ? '修改' : '添加') + '商品失败')
        }
    }

    // 获取一级或者二级分类列表的数据
    getCategorys = async (parentId) => {
        // 请求列表数据
        const reponse = await reqCategorys(parentId)
        const result = reponse.data
        if (result.status === 0) {
            const categorys = result.data.categorys
            if (parentId === 0) {
                // 一级分类列表
                this.initOptions(categorys)
            } else {
                return categorys
            }
        } else {
            message.error('获取品类信息失败')
        }
    }

    // 生成options数组
    initOptions = async (categorys) => {
        const options = categorys.map(
            item => ({
                value: item.id,
                label: item.categoryName,
                isLeaf: false, // 不是叶子
            })
        )

        // 如果是一个二级分类的更新
        const {isUpdate, product} = this
        const {pcategoryId, categoryId} = product
        if (isUpdate && pcategoryId !== '0') {
            // 获取对应的二级分类列表
            const subCategorys = await this.getCategorys(pcategoryId)
            // 生成对应的options
            const childOptions = subCategorys.map(
                item => ({
                    value: item.id,
                    label: item.categoryName,
                    isLeaf: true, // 是叶子
                })
            )
            // 关联到对应的一级options
            const targetOption = options.find(option => option.value===pcategoryId)
            targetOption.children = childOptions
        }

        // 更新options状态
        this.setState({options})
    }

    // 加载二级列表数据
    loadData = async selectedOptions => {
        // 得到选择的option对象
        const targetOption = selectedOptions[0]
        // 显示loading
        targetOption.loading = true

        // 根据选择的一级分类获取二级分类数据
        const subCategorys = await this.getCategorys(targetOption.value)
        // 隐藏loading
        targetOption.loading = false

        // 判断当前分类是否存在二级分类
        if (subCategorys && subCategorys.length > 0) {
            // 生成一个二级列表的options
            const childOptions = subCategorys.map(
                item => ({
                    value: item.id,
                    label: item.categoryName,
                    isLeaf: true, // 是叶子
                })
            )
            // 把当前childoptions关联到options上
            targetOption.children = childOptions
        } else { // 当前分类没有二级分类
            targetOption.isLeaf = true
        }

        // 更新options状态
        this.setState({
            options: [...this.state.options]
        })

    }

    componentDidMount () {
        // 获取一级分类列表数据
        this.getCategorys(0)
    }

    componentWillMount () {
        const product = this.props.location.state
        this.isUpdate = !!product // 判断是否更新的标识
        this.product = product || {}
    }

    render() {

        const {isUpdate, product} = this
        const {pcategoryId, categoryId, image, detail} = product
        // 级联分类的ID数组
        const categoryIds = []
        if (isUpdate) {
            if (pcategoryId === '0') { // 一级分类商品
                categoryIds.push(categoryId)
            } else { // 二级分类商品
                categoryIds.push(pcategoryId)
                categoryIds.push(categoryId)
            }
        }

        // 标题
        const title = (
            <span>
                <LinkButton onClick={() => this.props.history.goBack()}>
                    <ArrowLeftOutlined style={{marginRight: 5, fontSize: 16}}/>
                </LinkButton>
                <span>{isUpdate ? '修改商品' : '添加商品'}</span>
            </span>
        )

        // 指定item布局
        const formItemLayout = {
            labelCol: {span: 2},
            wrapperCol: {span: 5},
        }

        return (
            <div>
                <Card title={title}>
                    <Form {...formItemLayout} onFinish={this.submit}>
                        <Item label="商品名称" name="name" initialValue={product.productName} rules={[
                            {required: true, message: '商品名称不能为空!'}]}>
                            <Input placeholder='请输入商品名称'/>
                        </Item>
                        <Item label="商品描述" name="desc" initialValue={product.productDesc} rules={[
                            {required: true, message: '商品描述不能为空!'}]}>
                            <TextArea placeholder="请输入商品描述" allowClear autoSize={{minRows: 2, maxRows: 6}}/>
                        </Item>
                        <Item label="商品价格" name="price" initialValue={product.price} rules={[
                            {required: true, message: '商品价格不能为空!'},
                            {validator: (_, value) => {
                                if (value * 1 > 0) {
                                    return Promise.resolve()
                                } else {
                                    return Promise.reject('商品价格必须大于0')
                                }
                            }}]}>
                            <Input placeholder='请输入商品价格' prefix="¥" suffix="RMB" type='number'/>
                        </Item>
                        <Item label="商品分类" name="categoryIds" initialValue={categoryIds} rules={[
                            {required: true, message: '商品分类不能为空!'}]}>
                            <Cascader 
                                options={this.state.options} // 要显示的列表数据
                                loadData={this.loadData} // 选择某个列表项加载下一级列表的回调函数
                                placeholder="请指定商品分类" 
                            />
                        </Item>
                        <Item label="商品图片">
                            <PicturesWall ref={this.pw} image={image}/>
                        </Item>
                        <Item label="商品详情" labelCol={{span: 2}} wrapperCol={{span: 14}}>
                            <RichTextEditor ref={this.rte} detail={detail}/>
                        </Item>
                        <Item wrapperCol={{span: 16}}>
                            <Button type='primary' htmlType="submit" style={{marginLeft: 1023}}>提交</Button>
                        </Item>
                    </Form>
                </Card>
            </div>
        )
    }
}
